package xyz.gits.modules.system.service.impl;

import cn.hutool.extra.mail.MailUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import xyz.gits.modules.entity.Email;
import xyz.gits.modules.system.service.IMailService;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: 读钓
 * @date 2019-05-19 下午 4:35
 */
@Service
@Slf4j
public class MailServiceImpl implements IMailService {

    @Autowired
    public Configuration configuration;

    @Override
    public void send(Email mail) throws Exception {
        configuration.setClassForTemplateLoading(getClass(),"/template/");
        Template template = configuration.getTemplate(mail.getTemplate());
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(
                template, mail.getKvMap());

        MailUtil.sendHtml(mail.getEmail(), mail.getSubject(), content);
    }

    @Override
    public boolean sendCodeVerify(String userName, String email) throws Exception {
        Map<String, String> map = new HashMap<>(2);
        String id = IdWorker.getIdStr();
        map.put("userName", userName);
        // 生成4位验证码
        map.put("mailCode", id.substring(id.length() - 4));
        Email mail = Email.builder()
                .email(email)
                .subject("注册验证码")
                .kvMap(map)
                .template("mailCode.html").build();
        this.send(mail);
        return true;
    }
}